import { authInfo, authLogout } from '@/api/login'
import Router from 'vue-router'
import { Message } from 'element-ui'
import { getToken } from '@/utils/auth'
import router, { routerMap, constantRouterMap } from '@/router'
import { routeMenus } from './menus'

const user = {
  state: {
    token: getToken(),
    perRouter: [], // 按需加载的路由
    user: {}, // 用户信息
    menus: [], // 菜单
    halfMenu: [], // 过滤的下拉菜单['/system']
    perms: [], // 按钮权限
    webMenuArr: [] // 前端配置的路径
  },

  mutations: {
    SET_USER: (state, user) => {
      state.user = user
    },
    SET_MENUS: (state, menus) => {
      state.menus = menus
    },

    SET_TOKEN: (state, token) => {
      state.token = token
    },

    SET_PERMS: (state, perms) => {
      state.perms = perms
    },

    SET_ROUTES: (state, perRouter) => {
      state.perRouter = perRouter
    },
    SET_HALFMENU: (state, halfMenu) => {
      state.halfMenu = halfMenu
    },
    SET_WEB_MENUARR: (state, webMenuArr) => {
      state.webMenuArr = webMenuArr
    }
  },

  actions: {
    // 获取用户信息
    GetUserInfo({ commit, state }) {
      const readyPerms = []
      function getPermChildren(tree) {
        const childKey = 'childs'
        tree.forEach(item => {
          if (item.methodUrl && item.method !== null) {
            // readyPerms.push({ name: item.name, api: `${item.method} ${item.methodUrl}` })
            readyPerms.push(`${item.method} ${item.methodUrl}`)
          } else {
            if (item[childKey] && item[childKey].length > 0) {
              getPermChildren(item[childKey])
            }
          }
        })

        return readyPerms
        // return ['POST /city/org/batch/template', 'POST /city/plan/e/p/bm', 'POST /city/org/batch/import/{year}/{serial}']
      }

      return new Promise((resolve, reject) => {
        authInfo().then(res => {
          // 按需加载系统路由
          const list = [
            {
              children: [],
              component: routerMap[0].component,
              redirect: routerMap[0].redirect,
              path: routerMap[0].path
            },
            routerMap[1]
          ]

          const menuAuths = res.data.menuAuth
          menuAuths.forEach(item => {
            const obj = routerMap[0].children.find(ro => {
              return ro.path === item.url
            })
            if (!obj) return
            let childList = obj.children
            let childUrl = []
            if (item.childs && item.childs.length && item.type === 0) {
              childUrl = item.childs.map(ch => { return ch.url.replace(obj.path, '') })

              const list = obj.children.filter(ch => {
                return childUrl.includes('/' + ch.path) && item.type === 0
              })

              if (list.length) {
                childList = list
              }
            }
            obj.children = childList
            list[0].children.push(obj)
          })

          const perRouter = list.concat(constantRouterMap)
          commit('SET_ROUTES', perRouter)
          router.options.routes = perRouter
          router.matcher = new Router({ mode: 'history', base: process.env.VUE_APP_PUBLIC_PATH, routes: [] }).matcher
          router.addRoutes(perRouter)

          const siderBarMenu = routerMap[0].children // 前端本地的业务路由
          const halfMenuObj = siderBarMenu.filter(item => item.meta.isHalf)
          const data = res.data
          commit('SET_USER', data.user)
          // 如果是MOCK则放开菜单
          const userMenus = routeMenus // 用户可访问菜单
          // const userMenus = data.menuAuth // 用户可访问菜单
          if (userMenus.length) {
            commit('SET_MENUS', userMenus)
            // 可访问按钮
            commit('SET_PERMS', getPermChildren(userMenus))
            const webMenuArr = siderBarMenu.map(item => item.path) // 前端本地路由
            commit('SET_WEB_MENUARR', webMenuArr)
            commit('SET_HALFMENU', halfMenuObj.map(item => item.path))
          } else {
            Message.error('该账号无可访问内容！')
          }

          resolve(res)
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 登出
    LogOut({ commit }) {
      return new Promise((resolve, reject) => {
        authLogout()
          .then(() => {
            commit('SET_TOKEN', '')
            commit('SET_PERMS', [])
            commit('SET_MENUS', [])
            commit('SET_USER', {})
            // commit('SET_SYSTEM_NAME', '');
            resolve()
          })
          .catch(error => {
            reject(error)
          })
      })
    }
  }
}

export default user
